import time

import allure
import pytest
import requests
from requests import utils

from utils.debugtalk import DebugTalk
from utils.read_files_tools.read_extract_yaml import ReadYamlData
from utils.logging_tool.recordlog import logs
from config.operationConfig import OperationConfig
from config.setting import FILE_PATH

session = requests.Session()


@pytest.fixture(scope='session', autouse=True)
@allure.story("登录")
def system_login():
    try:
        base_url = OperationConfig().get_section_for_data('api_envi', 'host')
        # 1、获取密钥key
        url_key = base_url + "/UAMS/getKey" + f"?_={time.time()}"
        res = session.get(url=url_key)
        key = res.text

        # 将key（密钥） 写入到 extract.yaml 文件中
        ReadYamlData(yaml_file=FILE_PATH['EXTRACT']).write_yaml_data({'key': key})

        # 2、UAMS 登录
        # 从extract.yaml 文件中 读取存放的key（密钥），对登录密码进行加密
        read_key = (ReadYamlData(yaml_file=FILE_PATH['EXTRACT']).get_yaml_data())['key']

        # 需要加密的数据
        password_base = "admin"
        password_aes = DebugTalk().aes_encryption(str(password_base), read_key)

        url_uams = base_url + "/UAMS/login?order=3"
        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
        data = {
            "username": "admin",
            "password": password_aes,
            "returnURL": ""
        }
        res = session.post(url=url_uams, headers=headers, data=data, allow_redirects=True)

        # 3、PID 登录
        pwd_base = "admin"
        pwd_md5 = DebugTalk().md5_encryption(pwd_base)

        url_pid = base_url + "/pidcad/access/login"
        headers = {
            "Content-Type": "application/json;charset=UTF-8",
        }
        data = {
            "isCloud": "0",
            "name": "admin",
            "pwd": str(pwd_md5)
        }
        res = session.post(url=url_pid, headers=headers, data=data, allow_redirects=True)

        # 获取最终的cookie
        cookie = requests.utils.dict_from_cookiejar(session.cookies)
        # 将cookie 写入到 extract.yaml 文件中
        ReadYamlData(yaml_file=FILE_PATH['EXTRACT']).write_yaml_data({'Cookie': cookie})
        logs.info('xxx 系统登录成功')

        return res.text

    except Exception as e:
        logs.error(f'xxx系统 登录接口出现异常，导致后续接口无法继续运行，请检查程序！，{e}')
        exit()

